/*
 * utility.h
 *
 *  Created on: 2021��6��11��
 *      Author: Administrator
 */

#ifndef SRC_UTILITY_H_
#define SRC_UTILITY_H_

/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "timers.h"
/* Xilinx includes. */
#include "xil_printf.h"
#include "xparameters.h"

#include <stdio.h>

// #define configEnableLog  // log开启
#define rapidIO_testFlag // 监控口RapidIO与DMA测试

#define TIMER_ID	1
#define DELAY_10_SECONDS	10000UL
#define DELAY_1_SECOND		1000UL

typedef enum {
    EVENT_MONITOR_TIMEOUT,
    EVENT_CONFIGURE_OK,
    EVENT_S2MM,
    EVENT_MM2S,
    EVENT_DMA_ERROR,
    EVENT_DMA_TEST_ENABLE,
    EVENT_EXT_UART_TX_OK,
    EVENT_EXT_UART_RX_OK,
    eventID_3
}Event_ID;

typedef struct{
    Event_ID ID;
    int32_t src;
    void* pData;
}Event;

#define DELAY_WR		50
#define DELAY_CNT		200

void init_state();
void makeEvent(Event* pEvent,int32_t myId,Event_ID evtId, const void* pData);
void null_xil_printf( const char8 *ctrl1, ...);
void gw_sleep(int32_t cnt);

char* parse_fpga_version(uint32_t number);

void writeToRingBuffer(u8 *transferBuffer, u16 size);

#define FPGAVERSION_BASEADDRESS 0x44a50008

#ifndef configEnableLog
    #define xil_printf null_xil_printf
#endif

typedef struct{
    char strASCIICompileProfile[128]; 
}Version;


#define RING_BUFFER_SIZE 64
typedef struct{
    u8 *debug_buffer_array[RING_BUFFER_SIZE];
    u8 *tmp_rx_ptr;
    u16 debug_buffer_size[RING_BUFFER_SIZE];
    u8  debug_buffer_idx;
    u8  debug_read_idx;
    u16 debug_call_cnt;
}DebugRingBuffer;


typedef struct{
    u32 rapid_io_1_cnt;
    u32 rapid_io_2_cnt;
    u32 rapid_io_3_cnt;
    u32 rapid_io_4_cnt;
    u32 rapid_io_5_cnt;
    u32 doorbell_cnt;
    u32 send_en_1_cnt;
    u32 send_en_2_cnt;
    u32 send_en_doorbell_cnt;
    u8  send_en_doorbell_flag;
}debugCntState;

typedef struct{
    u32 tx_cnt;
    u32 rx_cnt;
    u32 rx_length;
    u32 tx_length;
    u8* test_TxPacket;
    u32 rx_error_cnt;
    u8  rx_error_ret; // RapidIO 测试检查错误返回值 
    u32 tx_error_cnt;
    u32 tx_test_cnt;
    u8  clear_cnt;
    u8  sendEnFlag;
    u8  sendEnCnt;
    u32 tx_120packet_cnt;
    debugCntState debug_cnt_state;
}DmaState;

typedef struct{
    u32 tx_cnt;
    u32 rx_cnt;
    u32 rx_length;
    u32 tx_length;
    u8* test_extUartRxBuffer;
    u8* test_extUartTxBuffer;
}ExtUartState;

typedef struct{
    u32 reg_sync_val;
    u8  time_cnt;
    u8  reset_num;
}AgcState;

typedef struct{
    Version version;
    int8_t flag_spi_configuring;
    int8_t flag_spi_configure_ok;
    int8_t cnt_spi_configure_failed;
    int32_t cnt_timer_call;
    int8_t flag_start_timer;
    u32 axi_address;
    AgcState agc_state;
    DmaState dma_state;
    ExtUartState ext_uart_state;
    DebugRingBuffer debug_fifo;
}State;

#include "xil_types.h"
#include "xil_io.h"

#define gw_ReadReg(Address)             \
    Xil_In32(Address)
#define gw_WriteReg(Address, Value)     \
    Xil_Out32(Address, Value)

#endif /* SRC_UTILITY_H_ */
